package com.dayou.handler;

import javax.servlet.http.HttpServletRequest;

import com.dayou.common.core.domain.AjaxResult;
import com.dayou.common.exception.BusinessException;
import com.dayou.common.exception.DemoModeException;
import com.dayou.common.utils.LogUtil;
import com.dayou.common.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理器
 * 
 */
@RestControllerAdvice(basePackages = "com.dayou")
public class GlobalExceptionHandler
{
    @Autowired
    private LogUtil logUtil;
    /**
     * 请求方式不支持
     */
    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public AjaxResult handleException(HttpRequestMethodNotSupportedException e)
    {
        e.printStackTrace();
        logUtil.error(e.getMessage());
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult notFount(RuntimeException e)
    {
        e.printStackTrace();
        logUtil.error("运行时异常:"+e.getMessage());
        //return AjaxResult.error("运行时异常:" + e.getMessage());
        return AjaxResult.error("程序运行时异常");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e)
    {
        e.printStackTrace();
        logUtil.error(e.getMessage());
        return AjaxResult.error("服务器发生错误");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Object businessException(HttpServletRequest request, BusinessException e)
    {
        e.printStackTrace();
        logUtil.error(e.getMessage());
        if (ServletUtils.isAjaxRequest(request))
        {
            return AjaxResult.error(e.getMessage());
        }
        else
        {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("errorMessage", e.getMessage());
            modelAndView.setViewName("error/business");
            return modelAndView;
        }
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult demoModeException(DemoModeException e)
    {
        e.printStackTrace();
        return AjaxResult.error("演示模式，不允许操作");
    }
}
